package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.TradeAreaInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "商户管理:商圈管理")
@RestController
@RequestMapping(value = "/admin/merParam/tradeAreaInfo")
public class TradeAreaInfoController extends BaseController {
    private long oprMenuId = 20000024;
    private String oprMenuName = "商户管理:商圈管理";
    private long chkMenuId = 20000024;
    private String chkMenuName = "商户管理:商圈管理";
    private String webNextUrl = "/admin/merParam/tradeAreaInfo/edit";

    @Autowired
    private ITradeAreaInfoService tradeAreaInfoService;

    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private AreaInfoService areaInfoService;

    @Autowired
    private IBizTmpService bizTmpService;

    @Autowired
    private IBizHisService bizHisService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @GetMapping(value = "/list")
    public Map<String, Object> findByPage(QueryRequest request, TradeAreaInfo entity) {
        return getDataTable(this.tradeAreaInfoService.findByPage(request, entity));
    }


    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map<String, Object> editShow(@ModelAttribute("tradeAreaInfo") TradeAreaInfo entity, Model model, HttpServletRequest request) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");

        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }
            // 审核：获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }

            TradeAreaInfo tradeAreaInfo = JSON.parseObject(bizdata, TradeAreaInfo.class);

            if (Common.isBlank(tradeAreaInfo)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            BeanUtils.copyProperties(tradeAreaInfo, entity);
            String auditStatus = tmp.getAuditStatus();
            if (BusinessContainer.status_41.equals(auditStatus)) {
                TradeAreaInfo oldEntity = tradeAreaInfoService.getById(id);
                TradeAreaInfo changeData = compEntity(entity, oldEntity);
                //修改时对比详情数据
                result.put("checkUpdate", "Y");
                result.put("changeData", StringEscapeUtils.escapeHtml4(JSON.toJSONString(changeData, SerializerFeature.WriteMapNullValue)));

            }
        } else {
            // 增加
            if ("add".equals(optFlag)) {
                // 获取当前登录用户信息
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                String instId = request.getParameter("instId") == null ? "" : request.getParameter("instId");
                String crtOrgId = "";
                if (user.isAdmin()) {
                    if (StringUtils.isEmpty(instId)) {
                        log.error("运营中心管理员新增数据必须先选择法人行！");
                        throw new RedpException("运营中心管理员新增数据必须先选择法人行！");
                    } else {
                        UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                        crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
                    }
                } else {
                    instId = (instId == null ? user.getInstId() : instId);
                    crtOrgId = user.getOrgCode();
                }

                entity.setId("0");
                entity.setTradeAreaCode("00000000");
                entity.setAuditStatus(BusinessContainer.status_01);
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_00);
                UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);
                entity.setInstId(org.getInstId());

            }
            // 修改，注销，停用，启用，详情，审批
            if ("upd".equals(optFlag) || "cancel".equals(optFlag) || "stop".equals(optFlag) ||
                    "start".equals(optFlag) || "detail".equals(optFlag)) {
                String id = request.getParameter("id") == null ? "" : request.getParameter("id");
                if (!"".equals(id)) {
                    entity = tradeAreaInfoService.getById(id);
                }
            }
        }


        result.put("optFlag", optFlag);
        result.put("entity", entity);
        //
        result.put("auditStatus", entity.getAuditStatus());
        result.put("tradeAreaStatus", entity.getTradeAreaStatus());
        result.put("crtOrgId", entity.getCrtOrgId());
        result.put("oprId", entity.getOprId());
        result.put("createTime", entity.getCreateTime());
        result.put("lastOprId", entity.getLastOprId());
        result.put("lastUpdateTime", entity.getLastUpdateTime());

        return result;
    }

    private TradeAreaInfo compEntity(TradeAreaInfo entity, TradeAreaInfo oldEntity) throws RedpException {
        TradeAreaInfo changeData = new TradeAreaInfo();
        if (Common.isBlank(entity) || Common.isBlank(oldEntity)) {
            throw new RedpException("获取详情数据异常");
        }

        if (!(StringUtils.equals(entity.getTradeAreaName(), oldEntity.getTradeAreaName()))) {
            changeData.setTradeAreaName(oldEntity.getTradeAreaName());
        } else {
            changeData.setTradeAreaName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getTradeAreaDesc(), oldEntity.getTradeAreaDesc()))) {
            changeData.setTradeAreaDesc(oldEntity.getTradeAreaDesc());
        } else {
            changeData.setTradeAreaDesc("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getBelongInstId(), oldEntity.getBelongInstId()))) {
            changeData.setBelongInstId(oldEntity.getBelongInstId());
            changeData.setBelongInstName(oldEntity.getBelongInstName());
        } else {
            changeData.setBelongInstId("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getBelongAreaCode(), oldEntity.getBelongAreaCode()))) {
            changeData.setBelongAreaCode(oldEntity.getBelongAreaCode());
            changeData.setBelongAreaName(oldEntity.getBelongAreaName());
        } else {
            changeData.setBelongAreaCode("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getManagementScope(), oldEntity.getManagementScope()))) {
            changeData.setManagementScope(oldEntity.getManagementScope());
        } else {
            changeData.setManagementScope("unChange--data");//提示前端数据未改变
        }
        return changeData;
    }

    @PostMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "auditRefuseReason", value = "拒绝原因", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "opt", value = "操作", required = false, dataType = "String")
    })
    public OperationResult editSave(@ModelAttribute("tradeAreaInfo") TradeAreaInfo entity, Model model, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        String managementScope = entity.getManagementScope() == null ? " " : entity.getManagementScope();
        entity.setManagementScope(managementScope);
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
            entity = tradeAreaInfoService.getById(entity.getId());
        } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
            menuId = String.valueOf(oprMenuId);
            String cancelReason = entity.getCancelReason();
            entity = tradeAreaInfoService.getById(entity.getId());
            entity.setCancelReason(cancelReason);
        } else {
            menuId = String.valueOf(oprMenuId);
        }

        return tradeAreaInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl);
    }


    /**
     * 审批
     *
     * @param entity
     * @param model
     * @param request
     * @return
     */
    @PostMapping(value = "/editPass")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String")
    })
    public OperationResult editpass(@ModelAttribute("tradeAreaInfo") TradeAreaInfo entity, Model model, HttpServletRequest request) throws RedpException {
        String id = request.getParameter("id");
        String optFlag = request.getParameter("optFlag");
        String auditRefuseReason = entity.getAuditRefuseReason();
        String cancelReason = entity.getCancelReason();
        String stopReason = entity.getStopReason();
        entity = tradeAreaInfoService.getById(id);
        entity.setAuditRefuseReason(auditRefuseReason);
        entity.setCancelReason(cancelReason);
        entity.setStopReason(stopReason);

        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }

        return tradeAreaInfoService.chkData(menuId, oprMenuName, entity, request, webNextUrl);
    }
    @DeleteMapping("/{ids}")
    public void delete(@PathVariable String ids) throws RedpException {
        String[] idsArr = ids.split(StringPool.COMMA);
        for (String s : idsArr) {
            TradeAreaInfo entity = tradeAreaInfoService.getById(s);
            java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
            String status = entity.getTradeAreaStatus();
            if (!BusinessContainer.status_03.equals(status)) {
                throw new RedpException("非新增审批拒绝的集团商户，不能进行删除");
            }
        }
        this.tradeAreaInfoService.getBaseMapper().deleteBatchIds(Arrays.asList(idsArr));
    }
    @GetMapping(value = "/unionAreaSelect2List" )

    public Map<String, Object> unionAreaSelect2List(QueryRequest request, @NotBlank(message = "{required}") String q) {
        return areaInfoService.areaInfoSelect2List(request,q);
    }
}
